package captcha

import (
	"errors"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/pkg/cache"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct {
	svcCtx *svc.ServiceContext
}

func (r RedisStore) Set(id string, value string) error {
	if err := cache.New(r.svcCtx.Redis).Set(CAPTCHA+id, value, 180*time.Second); err != nil {
		return errors.New("设置失败")
	}
	return nil
}

func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	res := cache.New(r.svcCtx.Redis).Get(key)
	if clear {
		cache.New(r.svcCtx.Redis).Delete(key)
	}
	return res
}

func (r RedisStore) Verify(id, answer string, clear bool) bool {
	v := r.Get(id, clear)
	return v == answer
}
